import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';
import { tap, switchMap, map } from 'rxjs/operators';
import {
  PermissionEnum,
  Model,
  DataPermission,
  SysroleDataPermissionPK,
} from 'src/app/domain/sparrow';
import { DataPermissionService } from 'src/app/service/data-permission.service';
import { ModelService } from 'src/app/service/model.service';
import { PermissionSelectComponent } from '../permission-select/permission-select.component';
import { SysroleSearchComponent } from '../sysrole-search/sysrole-search.component';

export interface AutocompleteOptionGroups {
  title: string;
  count?: number;
  children?: AutocompleteOptionGroups[];
}

@Component({
  selector: 'app-set-data-permission',
  templateUrl: './set-data-permission.component.html',
  styleUrls: ['./set-data-permission.component.css'],
})
export class SetDataPermissionComponent implements OnInit {
  @ViewChild(SysroleSearchComponent) sysroleSearch!: SysroleSearchComponent;

  permissionKeys: any[] = Object.keys(PermissionEnum).map((label) => ({
    label: PermissionEnum[label as keyof typeof PermissionEnum],
    value: label,
  }));

  inputValue?: string;

  dataScope: any[] = [
    { label: '本条数据', value: 'SELF_ONLY' },
    { label: '包含子孙', value: 'ALL_CHILDREN' },
  ];
  dataScopeSelected?: string;

  onChange(value: string): void {
    console.log(value);
  }
  models: Model[] = [];
  dataIds!: string[];
  constructor(
    private router: ActivatedRoute,
    private dataPermissionService: DataPermissionService,
    private modelService: ModelService
  ) {}

  ngOnInit(): void {
    console.log(this.router.params);
    // const models$:Observable<Model[]> = this.router.params.pipe(tap(params=>console.log(params)),
    //   switchMap(params=>
    //     this.modelService.getModelsInId(JSON.parse(params['ids'])).pipe(map(res => res = res.content))
    //   )
    // );
    // models$.subscribe(res=>{
    //    this.models = res;
    // });

    // const dataIds$: Observable<string[]>  = this.router.params.pipe(map(params=> JSON.parse(params['dataIds'])));
    // dataIds$.subscribe(res=>{
    //   this.dataIds =res
    // });
  }

  onClose(): void {
    console.log('tag was closed.');
  }
  radioValue: string = '';
  allChecked = false;
  indeterminate = true;

  updateAllChecked(): void {
    this.indeterminate = false;
    if (this.allChecked) {
      this.permissionKeys = this.permissionKeys.map((item) => ({
        ...item,
        checked: true,
      }));
    } else {
      this.permissionKeys = this.permissionKeys.map((item) => ({
        ...item,
        checked: false,
      }));
    }
  }

  updateSingleChecked(): void {
    if (this.permissionKeys.every((item) => !item.checked)) {
      this.allChecked = false;
      this.indeterminate = false;
    } else if (this.permissionKeys.every((item) => item.checked)) {
      this.allChecked = true;
      this.indeterminate = false;
    } else {
      this.indeterminate = true;
    }
  }

  @ViewChild(PermissionSelectComponent)
  permissionSelectComponent!: PermissionSelectComponent;
  addPermission() {
    if (this.radioValue === 'ADD') {
      this.dataPermissionService
        .addPermission(
          this.permissionOp(this.permissionSelectComponent.radioValue!)
        )
        .subscribe();
    } else {
      this.dataPermissionService
        .delPermission(
          this.permissionOp(this.permissionSelectComponent.radioValue!)
        )
        .subscribe();
    }
  }

  permissionOp(permissionType: string): DataPermission {
    let permissions: DataPermission = new DataPermission();
    this.dataIds.forEach((dataId) => {
      this.sysroleSearch.selectedUser?.forEach((user) => {
        this.permissionSelectComponent.listOfSelectedPermissionValue.forEach(
          (p) => {
            permissions.sysroleDataPermissionPKs.push({
              modelName: this.models[0].name,
              permission: p,
              permissionType: permissionType,
              sysroleId: user.id,
              dataId: dataId,
            });
          }
        );
      });
    });
    return permissions;
  }

  delPermission() {
    this.dataPermissionService
      .delPermission(
        this.permissionOp(this.permissionSelectComponent.radioValue!)
      )
      .subscribe();
  }
}
